package tools.httpdownloader.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpUtil
{
	private HttpURLConnection con = null;
	private URL srcURL = null;
	private String destFile = null;
	private BufferedReader bis = null;
	private FileWriter fos = null;

	private int len;
	private char[] buffer = new char[4096];

	public void disconnection()
	{
		try
		{
			if (bis != null)
			{
				bis.close();
				bis = null;
			}
			if (fos != null)
			{
				fos.close();
				fos = null;
			}
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}

		if (con != null)
		{
			con.disconnect();
			con = null;
		}
	}

	public boolean download(String srcURLString, File destdir)
			throws IOException
	{
		boolean failed = false;
		srcURL = new URL(srcURLString);
		if (!checkInput(srcURL, destdir))
		{
			return failed;
		}

		destFile = destFile
				+ "/"
				+ srcURLString.substring(srcURLString.lastIndexOf("/")
						+ "/".length());

		bis = new BufferedReader(new InputStreamReader(con.getInputStream()));
		fos = new FileWriter(destFile);

		while ((len = bis.read(buffer)) > 0)
		{
			fos.write(buffer, 0, len);
		}

		return failed;
	}

	public String download(String srcURLString, String destdir)
			throws MalformedURLException, IOException
	{
		srcURL = new URL(srcURLString);
		if (!checkInput(srcURL))
		{
			return "";
		}

		StringBuilder sb = new StringBuilder();
		destFile = destFile
				+ "/"
				+ srcURLString.substring(srcURLString.lastIndexOf("/")
						+ "/".length());

		bis = new BufferedReader(new InputStreamReader(con.getInputStream()));
		while ((len = bis.read(buffer)) > 0)
		{
			sb.append(buffer, 0, len);
		}
		return sb.toString();
	}

	private boolean checkInput(URL srcurl, File destdir)
	{
		if (destdir == null || destdir.isFile() == true)
		{
			return false;
		}
		if (destdir.exists() == false)
		{
			destdir.mkdirs();
		}
		return checkInput(srcurl);
	}

	private boolean checkInput(URL srcurl)
	{
		boolean checkPassed = true;
		try
		{
			con = (HttpURLConnection) srcurl.openConnection();
		}
		catch (MalformedURLException e)
		{
			checkPassed = false;
			System.err.println(e.getMessage());
		}
		catch (IOException e)
		{
			checkPassed = false;
			System.err.println(e.getMessage());
		}
		return checkPassed;
	}
}
